<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Index extends Backend
{
    protected $NoNeedLogin = ['login'];
    public $navTitle = "home";
    public function index()
    {
        $PostList = model('Post.Post')->select();
        $UserList = model('User.User')->select();
        $CommentList = model('Post.Comment')->select();
        $ProductList = model('Product.Product')->select();

        // $userid = cookie('LoginAdmin')['id'];
        // $records = model('User.Record')->where('userid', $userid)->order('createtime', 'desc')->select(10);

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'PostCount' => count($PostList),
            'UserCount' => count($UserList),
            'ProductCount' => count($ProductList),
            'CommentCount' => count($CommentList),
            // 'RecordsCount' => count($records),
        ]);
    }

    public function login()
    {
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? cookie('LoginAdmin') : '';

        if ($LoginAdmin) {
            $adminList = model('Admin')->select();

            $adminid = 0;

            foreach ($adminList as $key => $value) {
                $temp = md5($value['id'] . $value['salt']);

                if ($LoginAdmin == $temp) {
                    $adminid = $value['id'];
                    break;
                }
            }

            $Admin = model('Admin')->find($adminid);

            if (!$Admin) {
                cookie('LoginAdmin', null);
                $this->error('非法登录', url('admin/index/login'));
            }

            if ($Admin['state'] != 1) {
                cookie('LoginAdmin', null);
                $this->error('该账号被禁用');
            }

            $this->success('登录成功', url('admin/index/index'));
        }

        if ($this->request->isPost()) {
            // TODO 获取表单提交参数
            $formData = $this->request->param();

            // TODO 验证码
            if (!captcha_check($formData['vercode'])) $this->error('验证码错误');

            $admin = model('Admin')->where(['username' => $formData['username']])->find();

            $password = md5($formData['password'] . $admin['salt']);

            if ($password != $admin['password']) $this->error('密码错误');

            if ($admin['state'] != 1) {
                cookie('LoginAdmin', null);
                $this->error('该账号被禁用');
            }

            $LoginAdmin = md5($admin['id'] . $admin['salt']);
            // TODO 5天自动登录
            if (!empty($formData['rememberme']) && $formData['rememberme'] == 1) {
                cookie('LoginAdmin', $LoginAdmin, 5 * 24 * 3600 + time());
            } else {
                cookie('LoginAdmin', $LoginAdmin);
            }

            $this->success('登录成功', url('admin/index/index'));
        }

        // TODO 临时关闭/切换模板
        $this->view->engine->layout('loginLayout');
        return $this->fetch();
    }
}
